package com.maweirdos.gulimall.order.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJackson2MessageConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @Author: Maweirdos
 * @Date: 2024/5/5 18:07
 */
@Configuration
public class RabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @PostConstruct // RabbitConfig对象创建完成以后调用这个方法
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            /**
             * correlationData是消息的唯一id
             * 只要消息到达broker，ack就为true
             * cause是错误的原因
             */
            if (ack) {
                System.out.println("消息发送成功");
            } else {
                System.out.println("消息发送失败" + cause);
            }
        });

        /**
         * 设置消息丢失的回调,只要消息没有到达队列，就会触发这个回调
         * message：投递失败的消息
         * replyCode：响应码
         * replyText：响应的文本内容
         * exchange：交换机
         * routingKey：路由键
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("消息丢失" + message + "==="
                    + replyCode + "==="
                    + replyText + "==="
                    + exchange + "==="
                    + routingKey);
        });
    }
}
